package com.jav;

import com.jav.data.InvMovilData;
import com.jav.per.PersisSetup;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.Container;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.util.Resources;

public final class SetupForm extends Form {

    private final static String[] DATOS1 = new String[]{"SI", "NO"};
    private final static String[] DATOS2 = new String[]{"CODIGO", "DESCRIPCION", "BODEGA"};
    private static final VentanaEspera waiting = new VentanaEspera("CARGANDO...");
    private Button save;
    private ComboBox cb_verInformes = new ComboBox(DATOS1);
    private ComboBox cb_verValCaptura = new ComboBox(DATOS1);
    private ComboBox cb_ordenar = new ComboBox(DATOS2);
    private int ultimoVerInforme;
    private int ultimoOrdenar;

    public SetupForm() {

        super("CONFIGURACIÓN");
        Resources res;
        try {

            setLayout(new BoxLayout(BoxLayout.Y_AXIS));
            res = Datos.getInstance().getRes();

            save = new Button("GUARDAR", res.getImage("add.png"));
            save.setAlignment(CENTER);

            /*Borra y crear el nuevo RecordStoreP*/
            save.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent evt) {

                    int verInformes = cb_verInformes.getSelectedIndex();
                    int verCaptura = cb_verValCaptura.getSelectedIndex();
                    int ordenProductos = cb_ordenar.getSelectedIndex();

                    try {

                        PersisSetup setup = new PersisSetup();
                        setup.setVerInforme(verInformes);
                        setup.setVerValores(verCaptura);
                        setup.setOrdenProductos(ordenProductos);
                        Persistencia p = new Persistencia(InvMovilData.PERS_CONFIG);
                        p.save(setup.persist());
                        msgBox(0x8f00ff00, "OK!", "GUARDADO EXITOSO!");
                        

                        if (!Datos.getInstance().isVacioPro() && ultimoOrdenar != ordenProductos) {

                            if (Dialog.show("Ordenar?", "¿Desea re-ordenar los productos?", "SI", "NO")) {
                                new Thread(new Runnable() {

                                    public void run() {
                                        waiting.showModeless();
                                        Datos.getInstance().ordenarProductos();
                                        waiting.dispose();

                                    }
                                }).start();
                            }
                        }
                        if (ultimoVerInforme != verInformes) {
                            InvMovilMidlet.setMainForm(new Menu());
                        }

                    } catch (Exception e) {
                        msgBox(0x8f00ff00, "ERROR!", "error al guardar: " + e.getMessage());
                    }

                }
            });

            addCommand(new Command("Atrás", res.getImage("bck.png")) {

                public void actionPerformed(ActionEvent evt) {
                    new Thread(new Runnable() {

                        Form forma;

                        public void run() {
                            waiting.showModeless();
                            forma = new ExportForm();
                            waiting.dispose();
                            forma.show();

                        }
                    }).start();
                }
            });

            /***********************************************************/
            addComponent(createPair("Ver informes", cb_verInformes, 0));
            addComponent(createPair("Ver $$ Captura", cb_verValCaptura, 0));
            addComponent(createPair("Orden Productos", cb_ordenar, 0));
            addComponent(save);
            /***********************************************************/
            cargarDatos();
        } catch (Exception e) {
            Datos.getInstance().addLogs(e.getMessage());
        } finally {
            res = null;
        }
    }

    private void cargarDatos() {

        PersisSetup pd = Datos.getInstance().getPersisSetup();
        if (pd != null) {
            this.ultimoVerInforme = pd.getVerInforme();
            this.ultimoOrdenar = pd.getOrdenProductos();

            this.cb_verInformes.setSelectedIndex(this.ultimoVerInforme);
            this.cb_verValCaptura.setSelectedIndex(pd.getVerValores());
            this.cb_ordenar.setSelectedIndex(this.ultimoOrdenar);
        }

    }

    private Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label lb_text = new Label(label);
        Dimension d = lb_text.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        lb_text.setPreferredSize(d);
        pair.addComponent(BorderLayout.WEST, lb_text);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    private void msgBox(int color, String titulo, String msnError) {
        setTintColor(color);
        Dialog.show(titulo.toUpperCase(), msnError, new Command("ok"), new Command[]{new Command("ok")}, Dialog.TYPE_CONFIRMATION, null, 0, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 500));
    }
}
